#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = ["mousechsh_embed"]

'''
【和第三方接入举例】
django rest framework 对接：
==================
文件：app/views.py
------------------
import json
import os
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from .com.mousechsh.run.MouseChshEmbed import mousechsh_embed

inner_code = mousechsh_embed( os.path.abspath( __file__ ), 'auth-server', '--prefix=/auth/api' )

@api_view( [ 'POST' ] )
def enter( request ):
	headers = {}
	for item in request.headers:
		headers[ item ] = request.headers[ item ]
	result = inner_code.call( json.dumps( {
		'method': 'POST',
		'path': request.get_full_path(),
		'headers': headers,
		'body': str( request.body, 'UTF-8' )
	}, ensure_ascii = False ) )
	return Response( status = status.HTTP_200_OK, data = json.loads( result ) )
=================
文件：app/urls.py
-----------------
from django.conf.urls import url

from .views import enter

app_name = 'mousechsh_auth'

urlpatterns = [
	url( 'api/', enter ),
]
==================
文件：boot/urls.py
------------------
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
	path( 'auth/', include( 'app.urls' ) ),
] + static( settings.STATIC_URL, document_root = settings.STATIC_ROOT )
'''

import os
import sys

sys.path.insert(
	0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
)

from com.mousechsh.common.cmd.MouseChshCmd import mousechsh_cmd_call_from_cli
from com.mousechsh.common.sys.MouseChshLoader import mousechsh_loader
from com.mousechsh.common.log.MouseChshLog import \
	MOUSECHSH_LOG_LEVEL_FATAL, \
	MOUSECHSH_LOG_LEVEL_INFO, \
	mousechsh_logging, \
	mousechsh_logging_data, \
	mousechsh_logging_exception


# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# from com.mousechsh.run.MouseChshLogConfig import *
# from com.mousechsh.run.MouseChshEmbedConfig import *
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


def mousechsh_embed(*params):
	mousechsh_loader('com.mousechsh.run.MouseChshLogConfig')
	mousechsh_logging("开始初始化……", level=MOUSECHSH_LOG_LEVEL_FATAL)
	mousechsh_logging_data(sys.path, "环境变量【sys.path】：", level=MOUSECHSH_LOG_LEVEL_INFO)
	mousechsh_logging("传入参数数量：", len(params), level=MOUSECHSH_LOG_LEVEL_INFO)
	for i in range(0, len(params)):
		mousechsh_logging(i, ")", params[i], level=MOUSECHSH_LOG_LEVEL_INFO)

	obj = None
	try:
		mousechsh_loader('com.mousechsh.run.MouseChshEmbedConfig')
		obj = mousechsh_cmd_call_from_cli(params)

		if obj is None:
			mousechsh_logging("没有可执行的命令", level=MOUSECHSH_LOG_LEVEL_FATAL)

	except Exception as ex:
		mousechsh_logging_exception(ex, "遇到无法恢复的错误：", level=MOUSECHSH_LOG_LEVEL_FATAL)
		if obj is not None:
			obj.interrupt()

	mousechsh_logging("初始化完成。", level=MOUSECHSH_LOG_LEVEL_FATAL)
	return obj
